// 配置 API 密钥 (请替换为你的实际 API Key)
const API_KEY = 'YOUR_API_KEY_HERE';
const BASE_URL = 'https://api.openweathermap.org/data/2.5/weather';

// DOM 元素
const cityInput = document.getElementById('city-input');
const searchBtn = document.getElementById('search-btn');
const locationBtn = document.getElementById('location-btn');
const weatherInfo = document.getElementById('weather-info');
const errorMessage = document.getElementById('error-message');
const cityName = document.getElementById('city-name');
const temperature = document.getElementById('temperature');
const description = document.getElementById('description');
const feelsLike = document.getElementById('feels-like');
const humidity = document.getElementById('humidity');
const windSpeed = document.getElementById('wind-speed');
const updateTime = document.getElementById('update-time');

// 搜索按钮事件监听
searchBtn.addEventListener('click', () => {
    const city = cityInput.value.trim();
    if (city) {
        getWeatherByCity(city);
    }
});

// 回车键搜索
cityInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        const city = cityInput.value.trim();
        if (city) {
            getWeatherByCity(city);
        }
    }
});

// 定位按钮事件监听
locationBtn.addEventListener('click', () => {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            position => {
                const { latitude, longitude } = position.coords;
                getWeatherByCoordinates(latitude, longitude);
            },
            error => {
                showError('无法获取您的位置信息，请手动输入城市名称');
            }
        );
    } else {
        showError('您的浏览器不支持地理定位功能');
    }
});

// 根据城市名称获取天气
async function getWeatherByCity(city) {
    try {
        const response = await axios.get(BASE_URL, {
            params: {
                q: city,
                appid: API_KEY,
                units: 'metric',
                lang: 'zh_cn'
            }
        });
        displayWeather(response.data);
    } catch (error) {
        showError('无法找到该城市，请检查城市名称是否正确');
    }
}

// 根据经纬度获取天气
async function getWeatherByCoordinates(lat, lon) {
    try {
        const response = await axios.get(BASE_URL, {
            params: {
                lat: lat,
                lon: lon,
                appid: API_KEY,
                units: 'metric',
                lang: 'zh_cn'
            }
        });
        displayWeather(response.data);
    } catch (error) {
        showError('获取天气信息失败，请稍后重试');
    }
}

// 显示天气信息
function displayWeather(data) {
    // 更新天气信息
    cityName.textContent = `${data.name}, ${data.sys.country}`;
    temperature.textContent = Math.round(data.main.temp);
    description.textContent = data.weather[0].description;
    feelsLike.textContent = Math.round(data.main.feels_like);
    humidity.textContent = data.main.humidity;
    windSpeed.textContent = data.wind.speed.toFixed(1);
    
    // 格式化更新时间
    const date = new Date(data.dt * 1000);
    updateTime.textContent = date.toLocaleString('zh-CN');
    
    // 设置背景样式
    setWeatherBackground(data.weather[0].main);
    
    // 显示天气信息，隐藏错误信息
    weatherInfo.classList.remove('hidden');
    errorMessage.classList.add('hidden');
}

// 设置天气背景样式
function setWeatherBackground(weatherMain) {
    // 移除所有天气类名
    document.body.className = '';
    
    // 根据天气主类型添加对应类名
    switch (weatherMain.toLowerCase()) {
        case 'clear':
            document.body.classList.add('clear-sky');
            break;
        case 'clouds':
            document.body.classList.add('clouds');
            break;
        case 'rain':
            document.body.classList.add('rain');
            break;
        case 'drizzle':
            document.body.classList.add('drizzle');
            break;
        case 'thunderstorm':
            document.body.classList.add('thunderstorm');
            break;
        case 'snow':
            document.body.classList.add('snow');
            break;
        case 'mist':
        case 'haze':
            document.body.classList.add(weatherMain.toLowerCase());
            break;
        default:
            document.body.classList.add('clear-sky');
    }
}

// 显示错误信息
function showError(message) {
    errorMessage.querySelector('p').textContent = message;
    errorMessage.classList.remove('hidden');
    weatherInfo.classList.add('hidden');
}

// 页面加载时尝试获取当前位置天气
window.addEventListener('load', () => {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            position => {
                const { latitude, longitude } = position.coords;
                getWeatherByCoordinates(latitude, longitude);
            },
            error => {
                // 如果用户拒绝定位，不显示错误，让用户手动输入
                console.log('用户拒绝了定位请求');
            }
        );
    }
});